<template>
	<view class="chat-container page-root" ref="page" @scroll="onScroll" :style="containerStyle" @touchstart="handlePageTouch">
		<!-- 使用picshow组件 -->
		<picshow :show="showImmersiveBackground"></picshow>
		
		<ai-chat ref="aiChat" @ai-message="handleAIMessage"
			@messages-updated="handleMessagesUpdated" @loading="handleLoading" @error="handleSSEError"></ai-chat>

		<!-- iOS 18 风格导航栏 -->
		<view class="ios18-navbar" :class="{ 'immersive-navbar': showImmersiveBackground }" :style="{ paddingTop: statusBarHeight + 'px' }">
			<view class="navbar-content">
				<view class="navbar-left">
					<view class="nav-button" :class="{ 'immersive-button': showImmersiveBackground }" @click="goBack">
						<my-icon name="chevron-left" width="44rpx" height="44rpx" color="#ffffff" />
					</view>
				</view>
				<view class="navbar-center" @click="goToModelSelect">
					<view class="role-model-selector" :class="{ 'immersive-selector': showImmersiveBackground }">
						<text class="role-name">{{ roleName }}</text>
						<text class="model-name">({{ currentModelName }})</text>
					</view>
				</view>
				<view class="navbar-right">
					<view class="nav-button" :class="{ 'immersive-button': showImmersiveBackground }" @click="showGroupChatMenu">
						<my-icon name="more" width="44rpx" height="44rpx" color="#ffffff" />
					</view>
				</view>
			</view>
		</view>

		<!-- 群聊菜单抽屉 -->
		<view class="action-drawer" v-if="showGroupMenu" @click.self="showGroupMenu = false">
			<view class="action-drawer-panel" :class="{ 'drawer-show': showGroupMenu }">
				<view class="drawer-header">
					<text class="drawer-title">群聊管理</text>
					<view class="drawer-close" @click="showGroupMenu = false">
						<my-icon name="close" width="40rpx" height="40rpx" color="var(--text-secondary-color)" />
					</view>
				</view>
				<view class="action-drawer-content">
					<view class="action-item" @click="showRoleManager">
						<my-icon name="user-group" width="40rpx" height="40rpx" color="var(--text-secondary-color)" />
						<text class="action-item-text">管理群聊角色</text>
					</view>
					<view class="action-item" @click="clearHistory">
						<my-icon name="delete" width="40rpx" height="40rpx" color="var(--text-secondary-color)" />
						<text class="action-item-text">清除聊天记录</text>
					</view>
					<view class="action-item cancel" @click="showGroupMenu = false">
						<my-icon name="close" width="40rpx" height="40rpx" color="var(--text-secondary-color)" />
						<text class="action-item-text">取消</text>
					</view>
				</view>
			</view>
		</view>

		<!-- 角色管理模态框 -->
		<view class="edit-modal-mask" v-if="showRoleManagerModal" @click.self="cancelRoleChanges">
			<view class="edit-modal-container role-manager-modal" :class="{ 'modal-show': showRoleManagerModal }">
				<view class="modal-header">
					<text class="modal-title">管理群聊角色</text>
					<view class="modal-close" @click="cancelRoleChanges">
						<my-icon name="close" width="40rpx" height="40rpx" color="var(--text-secondary-color)" />
					</view>
				</view>
				<view class="edit-modal-content">
					<view class="role-manager-section">
						<text class="section-title">当前群聊角色</text>
						<view class="role-list">
							<view v-for="role in tempGroupChatRoles" :key="role.id" class="role-item-manager">
								<image class="role-avatar" :src="role.avatar" mode="aspectFill"></image>
								<text class="role-name">{{ role.name }}</text>
								<view class="role-action" @click="removeRoleFromChat(role.id)">
									<my-icon name="delete" width="32rpx" height="32rpx"
										color="var(--text-secondary-color)" />
								</view>
							</view>
							<view v-if="tempGroupChatRoles.length === 0" class="empty-tip">
								<text>没有角色</text>
							</view>
						</view>
					</view>

					<view class="role-manager-section">
						<text class="section-title">可添加的角色</text>
						<view class="role-list">
							<view v-for="role in tempAvailableRoles" :key="role.id" class="role-item-manager">
								<image class="role-avatar" :src="role.avatar" mode="aspectFill"></image>
								<text class="role-name">{{ role.name }}</text>
								<view class="role-action" @click="addRoleToChat(role.id)">
									<my-icon name="add" width="32rpx" height="32rpx"
										color="var(--text-secondary-color)" />
								</view>
							</view>
							<view v-if="tempAvailableRoles.length === 0" class="empty-tip">
								<text>没有可添加的角色</text>
							</view>
						</view>
					</view>
				</view>
				<view class="modal-footer">
					<view class="edit-actions">
						<my-button @click="confirmRoleChanges" type="primary" size="mini" class="edit-btn"
							:disabled="!pendingRoleChanges">
							{{ pendingRoleChanges ? '保存更改' : '完成' }}
						</my-button>
					</view>
				</view>
			</view>
		</view>

		<!-- 消息列表区域 -->
		<view id="messageList" class="message-list" :class="{ 'immersive-message-list': showImmersiveBackground }" :style="messageListStyle">
			<view class="messages-container">
				<view class="message" v-for="(message, index) in messages" :key="message.id || index"
					:class="[message.type, { 'thinking': message.isThinking, 'immersive-message': showImmersiveBackground }]">
					<view class="message-content"
						:class="{ 'assistant-message': message.type === 'assistant', 'user-message': message.type === 'user', 'immersive-content': showImmersiveBackground }">
						<view v-if="message.type === 'assistant' && message.reasoning_content" class="reasoning-card"
							:class="{ expanded: message.isReasoningExpanded }">
							<view class="reasoning-header" @click="toggleReasoning(index)">
								<my-icon :name="message.isReasoningExpanded ? 'chevron-down' : 'chevron-right'"
									width="32rpx" height="32rpx" class="reasoning-icon" color="#ffffff" />
								<view class="reasoning-title">思考过程
									{{ message.isReasoningExpanded ? '(收起)' : '(展开)' }}</view>
							</view>
							<view class="reasoning-body" :class="{ collapsed: !message.isReasoningExpanded }">
								<view>{{ message.reasoning_content }}</view>
							</view>
						</view>
						<view class="answer-content" style="background: #0001;">
							<text class="message-text" style="color: #ffffffc0;">{{ message.content }}</text>
							<view v-if="message.isThinking" class="thinking-dots">
								<text>.</text>
								<text>.</text>
								<text>.</text>
							</view>
						</view>
					</view>
					<!-- 消息操作按钮 -->
					<view class="message-actions" v-if="!message.isThinking">
						<view class="action-buttons">
							<view class="action-btn copy" @click="handleCopyMessage(message)">
								<my-icon name="copy" width="32rpx" height="32rpx" color="#ffffff" />
							</view>
							<view class="action-btn edit" v-if="message.type === 'user'"
								@click="handleEditMessage(message)">
								<my-icon name="edit" width="32rpx" height="32rpx" color="#ffffff" />
							</view>
							<view class="action-btn delete" @click="handleDeleteMessage(message)">
								<my-icon name="delete" width="32rpx" height="32rpx" color="#ffffff" />
							</view>
						</view>
					</view>
				</view>
			</view>
			<view style="height: 32rpx;"></view>
		</view>

		<!-- 操作抽屉 -->
		<view class="action-drawer" v-if="showActionDrawer" @click.self="showActionDrawer = false">
			<view class="action-drawer-panel" :class="{ 'drawer-show': showActionDrawer }">
				<view class="drawer-header">
					<text class="drawer-title">{{ actionDrawerTitle }}</text>
					<view class="drawer-close" @click="showActionDrawer = false">
						<my-icon name="close" width="40rpx" height="40rpx" color="var(--text-secondary-color)" />
					</view>
				</view>
				<view class="action-drawer-content">
					<view class="action-item" @click="handleEditMessage"
						v-if="selectedMessage && selectedMessage.type === 'user'">
						<my-icon name="edit" width="40rpx" height="40rpx" color="var(--text-secondary-color)" />
						<text class="action-item-text">编辑消息</text>
					</view>
					<view class="action-item" @click="handleCopyMessage">
						<my-icon name="copy" width="40rpx" height="40rpx" color="var(--text-secondary-color)" />
						<text class="action-item-text">复制内容</text>
					</view>
					<view class="action-item delete" @click="handleDeleteMessage">
						<my-icon name="delete" width="40rpx" height="40rpx" color="var(--text-secondary-color)" />
						<text class="action-item-text">删除消息</text>
					</view>
					<view class="action-item cancel" @click="showActionDrawer = false">
						<my-icon name="close" width="40rpx" height="40rpx" color="var(--text-secondary-color)" />
						<text class="action-item-text">取消</text>
					</view>
				</view>
			</view>
		</view>

		<!-- 编辑消息模态框 -->
		<view class="edit-modal-mask" v-if="showEditDrawer" @click.self="showEditDrawer = false">
			<view class="edit-modal-container" :class="{ 'modal-show': showEditDrawer }">
				<view class="modal-header">
					<text class="modal-title">编辑消息</text>
					<view class="modal-close" @click="showEditDrawer = false">
						<my-icon name="close" width="40rpx" height="40rpx" color="var(--text-secondary-color)" />
					</view>
				</view>
				<view class="edit-modal-content">
					<textarea :adjust-position='false' class="edit-textarea" v-model="editingContent"
						placeholder="请输入新的消息内容" :maxlength="-1" :auto-height="true" :cursor-spacing="20" />
				</view>
				<view class="modal-footer">
					<view class="edit-actions">
						<my-button @click="showEditDrawer = false" type="default" size="mini"
							class="edit-btn cancel-btn">取消</my-button>
						<my-button @click="confirmEditMessage" type="primary" size="mini" class="edit-btn"
							:disabled="!editingContent.trim() || editingContent.trim() === (selectedMessage && selectedMessage.content)">保存</my-button>
					</view>
				</view>
			</view>
		</view>

		<!-- iOS 18 风格输入区域 -->
		<view class="ios18-input-container" :class="{ 'immersive-input': showImmersiveBackground }">
			<!-- 高级角色选择器 -->
			<view class="adult-roles-selector">
				<scroll-view scroll-x="true" class="roles-scroll" show-scrollbar="false">
					<view class="roles-list">
						<view v-for="role in groupChatRoles" :key="role.id" class="role-item"
							:class="{ 'selected': isRoleSelected(role.id) }" @click="toggleRoleSelection(role.id)">
							<text class="role-name">{{ role.name }}</text>
							<text v-if="isRoleSelected(role.id)" class="role-order">{{ getRoleOrder(role.id) }}</text>
						</view>
					</view>
				</scroll-view>
			</view>

			<!-- 未激活状态的输入提示区域 -->
			<view v-if="!isInputActive" class="input-wrapper" @click="activateInput">
				<view class="inactive-input-box">
					<text class="input-placeholder">输入消息...</text>
				</view>
				<view class="send-button-wrapper">
					<my-button disabled class="ios18-send-btn" type="primary" size="mini">
						<my-icon name="send" width="36rpx" height="36rpx" color="#000000" />
					</my-button>
				</view>
			</view>
			
			<!-- 激活状态的输入区域 -->
			<view v-if="isInputActive" class="input-wrapper active-input-wrapper" :style="inputContainerStyle" @touchstart.stop>
				<textarea :key="inputMessagekey" :auto-height="true" @input="handleInput" placeholder="输入消息..."
					confirm-type="send" @confirm="sendMessage" :rows="1" :maxrows="3" class="ios18-input-box" :adjust-position='false'
					:show-confirm-bar="false" :cursor-spacing="10" :auto-focus="true" @blur="handleInputBlur" />
				<view class="send-button-wrapper" :class="{ 'send-active': inputMessage.trim() }">
					<my-button @click="sendMessage" :disabled="isLoading || !inputMessage.trim()" class="ios18-send-btn"
						type="primary" size="mini">
						<my-icon name="send" width="36rpx" height="36rpx" color="#000000" />
					</my-button>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
import roleManager from '@/store/role.js'
import modelManager from '@/store/model.js'
import settingsManager from '@/store/settings.js'
import groupChatManager from '@/store/group-chat.js'
import { MessageType } from '@/store/group-chat.js'
import Picshow from '@/components/picshow/picshow.vue'

export default {
	components: {
		Picshow
	},
	
	data() {
		return {
			roleId: '',
			roleName: '',
			roleAvatar: '',
			inputMessage: '',
			inputMessagekey: 0,
			messages: [],
			isLoading: false,
			retryCount: 0,
			maxRetries: 3,
			statusBarHeight: 0,
			navbarHeight: 0,
			isAtBottom: true,
			showActionDrawer: false,
			selectedMessage: null,
			actionDrawerTitle: '消息操作',
			showEditDrawer: false,
			editingContent: '',
			modelManager,
			currentModelId: '',
			// 高级角色选择相关数据
			selectedRoles: [],
			adultRoles: [],
			// 群聊管理相关数据
			showGroupMenu: false,
			showRoleManagerModal: false,
			currentGroupId: '',
			groupChatRoles: [],
			availableRoles: [],
			// 角色变更临时存储
			tempGroupChatRoles: [],
			tempAvailableRoles: [],
			pendingRoleChanges: false,
			// 双重输入框相关数据
			isInputActive: false,
			jianpanHeight: 0,
			sysInfo: uni.getSystemInfoSync(),
			// 沉浸模式相关
			showImmersiveBackground: false,
			// 样式相关
			containerStyle: {
				backgroundColor: 'rgb(18, 18, 20)'
			},
			messageListStyle: {
				backgroundColor: 'rgb(18, 18, 20)'
			},
		}
	},

	computed: {
		// 获取当前模型名称
		currentModelName() {
			const model = modelManager.models.find(m => m.id === this.currentModelId);
			return model ? model.name : '未知模型';
		},
		inputContainerStyle() {
			if (this.isInputActive) {
				return {
					position: 'fixed',
					bottom: `${this.jianpanHeight}px`,
					left: '16px',
					right: '16px',
					width: 'auto',
					zIndex: 101
				};
			}
			return {};
		}
	},

	watch: {
		// 监听模型变化
		'modelManager.currentModel': {
			handler(newModelId) {
				if (newModelId !== this.currentModelId) {
					this.currentModelId = newModelId;
					this.handleModelChanged();
				}
			},
			immediate: true
		}
	},

	onLoad(options) {
		// 获取状态栏高度
		this.statusBarHeight = uni.getSystemInfoSync().statusBarHeight;

		// 设置CSS变量
		// #ifdef H5
		document.documentElement.style.setProperty('--status-bar-height', `${this.statusBarHeight}px`);
		document.documentElement.style.setProperty('--navbar-height', `${this.statusBarHeight + 56}px`);
		// #endif

		// #ifndef H5
		// App环境下通过类名方式设置
		this.navbarHeight = this.statusBarHeight + 56;
		// #endif

		// 设置当前模型ID
		this.currentModelId = modelManager.currentModel;

		// 检查是否有群聊ID
		if (options.groupId) {
			console.log('[群聊] 加载群聊:', options.groupId);
			this.loadGroupChatInfo(options.groupId);
		}
		// 兼容旧版本，检查是否有角色ID列表
		else if (options.roles) {
			console.log('[群聊] 使用角色列表创建临时群聊');
			try {
				const roleIds = JSON.parse(options.roles);
				this.selectedRoles = roleIds;
				// 设置群聊名称
				this.roleName = "临时群聊";
				// 加载高级角色列表
				this.loadAdultRoles();
			} catch (e) {
				console.error('[群聊] 解析角色列表失败:', e);
				this.showErrorAndNavigateBack('无效的角色列表');
			}
		} else {
			console.error('[群聊] 未提供群聊ID或角色列表');
			this.showErrorAndNavigateBack('缺少必要参数');
		}

		// 在页面加载完成后滚动到底部
		this.$nextTick(() => {
			this.scrollToBottom(false);
		});

		// 添加SSE关闭事件监听
		uni.$on('sse-closed', this.handleSSEClosed);

		// 添加键盘高度变化监听
		uni.onKeyboardHeightChange(this.keyBodyHeightWatch);
		
		// 添加设置变更事件监听
		uni.$on('settingsChange', this.handleSettingsChange);
		
		// 检查是否开启沉浸模式
		this.checkImmersiveMode();
	},

	onUnload() {
		// 清理事件监听
		uni.$off('sse-closed', this.handleSSEClosed);
		// 移除键盘高度变化监听
		uni.offKeyboardHeightChange(this.keyBodyHeightWatch);

		// 保存群聊消息历史
		if (this.currentGroupId) {
			try {
				// 过滤出非思考中的消息
				const completedMessages = this.messages.filter(msg => !msg.isThinking);
				
				// 使用groupChatManager保存群聊历史
				groupChatManager.saveGroupChatHistory(this.currentGroupId, completedMessages).catch(error => {
					console.error('[群聊] 退出页面时保存历史消息失败:', error);
				});
				console.log('[群聊] 退出页面时保存历史消息:', completedMessages.length);
			} catch (error) {
				console.error('[群聊] 退出页面时保存历史消息异常:', error);
			}
		}
		
		// 清理事件监听
		uni.$off('settingsChange', this.handleSettingsChange);
	},

	onShow() {
		// 检查并更新当前模型信息
		if (this.currentModelId !== modelManager.currentModel) {
			this.currentModelId = modelManager.currentModel;
			this.handleModelChanged();
		}

		// 检查沉浸模式状态
		this.checkImmersiveMode();
	},

	methods: {
		// 显示错误并返回上一页
		showErrorAndNavigateBack(message) {
			uni.showToast({
				title: message,
				icon: 'none',
				duration: 2000
			});
			setTimeout(() => uni.navigateBack(), 2000);
		},

		// 添加助手消息
		addAssistantMessage(content) {
			// 创建新消息对象
			const message = {
				id: Date.now().toString(36) + Math.random().toString(36).substr(2),
				type: MessageType.ASSISTANT,
				content: content,
				timestamp: Date.now()
			};

			this.messages.push(message);
			this.scrollToBottom();

			return message;
		},

		// 添加用户消息
		addUserMessage(content) {
			// 创建新消息对象
			const message = {
				id: Date.now().toString(36) + Math.random().toString(36).substr(2),
				type: MessageType.USER,
				content: content,
				timestamp: Date.now()
			};

			this.messages.push(message);
			this.scrollToBottom();

			return message;
		},

		// 添加思考中的消息
		addThinkingMessage(roleId = null, roleName = null) {
			const messageId = 'thinking_' + Date.now() + '_' + Math.floor(Math.random() * 1000);
			
			// 创建带有角色信息的思考消息
			const thinkingMessage = {
				id: messageId,
				type: 'assistant',
				content: '',
				isThinking: true,
				timestamp: Date.now()
			};
			
			// 如果提供了角色ID和名称，添加到消息中
			if (roleId) {
				thinkingMessage.roleId = String(roleId);
			}
			
			if (roleName) {
				thinkingMessage.roleName = roleName;
			}
			
			// 将消息添加到消息列表
			this.messages.push(thinkingMessage);
			
			// 发出消息更新事件，确保UI更新
			this.$emit('messages-updated', this.messages);
			
			// 滚动到底部
			this.scrollToBottom(true);
			
			console.log(`[聊天] 添加思考消息 ID=${messageId}${roleId ? ` 角色=${roleName}(${roleId})` : ''}`);
			
			return thinkingMessage;
		},

		// 更新消息
		updateMessage(messageId, updates) {
			const index = this.messages.findIndex(msg => msg.id === messageId);
			if (index === -1) return null;

			// 更新本地消息
			const updatedMessage = {
				...this.messages[index],
				...updates
			};
			this.$set(this.messages, index, updatedMessage);

			return updatedMessage;
		},

		// 删除消息
		removeMessage(messageId) {
			const index = this.messages.findIndex(msg => msg.id === messageId);
			if (index === -1) return false;

			// 从本地删除
			this.messages.splice(index, 1);

			return true;
		},

		// 查找最后一条用户消息
		findLastUserMessage() {
			for (let i = this.messages.length - 1; i >= 0; i--) {
				if (this.messages[i].type === MessageType.USER) {
					return this.messages[i];
				}
			}
			return null;
		},

		// 获取最后一条消息
		getLastMessage() {
			return this.messages.length > 0 ? this.messages[this.messages.length - 1] : null;
		},

		// 获取已完成的消息列表（用于发送给AI）
		getCompletedMessages() {
			// 准备API消息数组
			let apiMessages = [];

			// 过滤出已完成的消息并转换为API格式
			const conversationMessages = this.messages
				.filter(msg => !msg.isThinking && msg.content && msg.content.trim() !== '')
				.map(msg => ({
					role: msg.type === MessageType.USER ? 'user' : 'assistant',
					content: msg.content
				}));

			// 添加对话消息
			apiMessages = apiMessages.concat(conversationMessages);

			console.log('[消息处理] 总消息数量:', apiMessages.length);

			return apiMessages;
		},

		// 构建群聊系统提示 - 优化版本
		buildGroupChatPrompt(role) {
			// 如果没有提供角色，返回简单的默认提示
			if (!role) {
				return `你是一个角色扮演ai,正在进行多人角色扮演。`;
			}

			// 如果角色有prompt，结合其prompt构建提示
			return `
【对话规则】
1. 你只能以${role.name}的身份发言，不要代表或模仿其他角色
2. 不要在回复中重复你的角色名，系统会自动添加
3. 如果用户明确指定了其他角色回答问题，那就一定不是在对你说话，做你符合上下文、人设的回答
4. 即使用户要求你扮演其他角色，你也必须拒绝，并继续扮演${role.name}
5. 判断上一个发言是不是ai,需要同时处理，但是务必对用户有所相应
6. 不需要在回复中添加角色名，系统会自动添加

${role.prompt || ''}
`;
		},

		// 处理AI消息流式更新
		handleAIMessage(delta) {
			// 处理普通AI消息
			const currentMsg = this.getLastMessage();
			if (!currentMsg || currentMsg.type !== MessageType.ASSISTANT) return;

			let updates = {};

			// 更新推理内容
			if (delta.reasoning_content) {
				updates.reasoning_content = (currentMsg.reasoning_content || '') + delta.reasoning_content;
			}

			// 更新消息内容
			if (delta.content) {
				// 清理内容中的[DONE]标记，但不处理消息完成状态
				let cleanContent = delta.content.replace(/\[DONE\]/g, '');
				updates.content = (currentMsg.content || '') + cleanContent;
			}

			// 应用更新
			if (Object.keys(updates).length > 0) {
				this.updateMessage(currentMsg.id, updates);
				this.scrollToBottom(false);
			}
		},

		// 处理消息更新
		handleMessagesUpdated(messages) {
			// 处理普通消息更新
			if (messages.length > 0) {
				const lastMessage = messages[messages.length - 1];
				if (lastMessage.role === 'assistant' && lastMessage.content) {
					const currentMsg = this.getLastMessage();

					// 检查当前是否有思考中的助手消息
					if (currentMsg && currentMsg.type === MessageType.ASSISTANT && currentMsg.isThinking) {
						// 更新现有的思考消息
						this.updateMessage(currentMsg.id, {
							content: lastMessage.content,
							isThinking: false
						});
						console.log('[消息更新] 更新现有思考消息');
						this.scrollToBottom(true);
					} else if (currentMsg && currentMsg.type === MessageType.ASSISTANT && !currentMsg.isThinking) {
						// 如果最后一条消息是已完成的助手消息，检查内容是否需要更新
						if (currentMsg.content !== lastMessage.content) {
							this.updateMessage(currentMsg.id, {
								content: lastMessage.content
							});
							console.log('[消息更新] 更新现有助手消息内容');
							this.scrollToBottom(true);
						}
					} else {
						// 如果当前没有助手消息或最后一条不是助手消息，则创建一个新的
						console.log('[消息更新] 创建新的助手消息');
						this.addAssistantMessage(lastMessage.content);
						this.scrollToBottom(true);
					}
				}
			}
		},

		// 处理加载状态变化
		handleLoading(loading) {
			this.isLoading = loading;

			// 如果加载结束，隐藏加载提示
			if (!loading) {
				uni.hideLoading();
			}
		},

		// 切换推理内容的展开/折叠状态
		toggleReasoning(index) {
			if (this.messages[index]) {
				const isExpanded = !this.messages[index].isReasoningExpanded;
				this.updateMessage(this.messages[index].id, {
					isReasoningExpanded: isExpanded
				});
			}
		},

		// 处理SSE错误
		handleSSEError(err) {
			console.error('[SSE] 错误:', err);

			// 处理SSE关闭事件
			if (err?.type === 'SSE_CLOSED') {
				// 使用专门的处理方法
				this.handleSSEClosed();
				return;
			}

			// 处理组件错误
			if (err?.type === 'COMPONENT_ERROR') {
				console.error('[组件错误]', err.message);
				uni.hideLoading();
				uni.showToast({
					title: err.message || '组件错误',
					icon: 'none'
				});
				return;
			}

			// 隐藏加载提示
			uni.hideLoading();

			if (this.retryCount < this.maxRetries) {
				this.retryCount++;
				uni.showToast({
					title: `连接失败，正在重试(${this.retryCount}/${this.maxRetries})`,
					icon: 'none',
					duration: 2000
				});

				setTimeout(() => {
					const lastUserMessage = this.findLastUserMessage();
					if (lastUserMessage) {
						this.retryMessage(lastUserMessage.content);
					}
				}, 2000);
			} else {
				this.isLoading = false;
				this.retryCount = 0;

				const lastMessage = this.getLastMessage();
				if (lastMessage && (!lastMessage.content || lastMessage.content.trim() === '')) {
					this.removeMessage(lastMessage.id);
				}

				uni.showModal({
					title: '连接失败',
					content: '是否重新发送消息？',
					success: (res) => {
						if (res.confirm) {
							const lastUserMessage = this.findLastUserMessage();
							if (lastUserMessage) {
								this.retryCount = 0;
								this.retryMessage(lastUserMessage.content);
							}
						} else {
							this.isLoading = false;
							this.retryCount = 0;
						}
					}
				});
			}
		},

		// 重试发送消息
		async retryMessage(content) {
			if (this.isLoading) return;

			const lastMessage = this.getLastMessage();
			let aiMessage;

			if (lastMessage && lastMessage.type === MessageType.ASSISTANT) {
				// 更新现有AI消息
				aiMessage = this.updateMessage(lastMessage.id, {
					content: '',
					reasoning_content: '',
					isThinking: true,
					isReasoningExpanded: false
				});
			} else {
				// 创建新的AI消息
				aiMessage = this.addThinkingMessage();
			}

			// 获取历史消息，但排除最新一条用户消息（避免重复）
			const historyMessages = this.getCompletedMessages();
			let processHistoryMessages = historyMessages;
			
			// 检查最后一条消息是否是用户消息
			if (historyMessages.length > 0 && historyMessages[historyMessages.length - 1].role === 'user') {
				// 排除最后一条用户消息，避免重复
				processHistoryMessages = historyMessages.slice(0, -1);
			}
			
			console.log('[重试] 使用历史消息, 数量:', processHistoryMessages.length);

			// 添加安全检查，确保aiChat组件存在
			if (this.$refs.aiChat) {
				// 处理多角色串联对话
				this.processMultiRoleChat(content, processHistoryMessages);
			} else {
				console.error('[重试] AI聊天组件引用不可用');
				uni.showToast({
					title: '聊天组件未就绪',
					icon: 'none'
				});
				// 恢复消息状态
				if (aiMessage) {
					this.updateMessage(aiMessage.id, {
						isThinking: false
					});
				}
			}
		},

		// 滚动到底部
		scrollToBottom(withAnimation = true) {
			this.isAtBottom = true;

			setTimeout(() => {
				// #ifdef H5
				if (withAnimation) {
					window.scrollTo({
						top: document.body.scrollHeight,
						behavior: 'smooth'
					});
				} else {
					window.scrollTo(0, document.body.scrollHeight);
				}
				// #endif

				// #ifdef APP-PLUS || MP
				uni.pageScrollTo({
					scrollTop: 99999, // 使用一个足够大的值确保滚动到底部
					duration: withAnimation ? 300 : 0
				});
				// #endif
			}, 100);
		},

		// 处理滚动事件
		onScroll(e) {
			// #ifdef H5
			// 获取页面滚动信息
			const h5ScrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;
			const windowHeight = window.innerHeight;
			const documentHeight = document.documentElement.scrollHeight;

			// 计算距离底部的距离
			const distanceFromBottom = documentHeight - (h5ScrollTop + windowHeight);
			this.isAtBottom = distanceFromBottom < 150;
			// #endif

			// #ifdef APP-PLUS || MP
			// App环境下使用事件对象获取滚动位置
			const appScrollTop = e.detail ? e.detail.scrollTop : 0;

			// 获取页面和容器的高度信息
			const query = uni.createSelectorQuery();
			query.select('.page-root').boundingClientRect().exec(pageRes => {
				if (!pageRes || !pageRes[0]) return;

				query.select('.messages-container').boundingClientRect().exec(containerRes => {
					if (!containerRes || !containerRes[0]) return;

					const pageHeight = pageRes[0].height;
					const contentHeight = containerRes[0].height;

					// 计算距离底部的距离
					const distanceFromBottom = contentHeight - (appScrollTop + pageHeight);
					this.isAtBottom = distanceFromBottom < 150;
				});
			});
			// #endif
		},

		// 处理多角色串联对话
		async processMultiRoleChat(userMsg, historyMessages) {
			this.isLoading = true;
			const selectedRoles = this.getSelectedAdultRolesInfo();
			
			// 如果没有选中角色，使用默认对话
			if (!selectedRoles?.length) {
				const msg = this.addThinkingMessage();
				
				try {
					// 创建包含系统提示的历史记录
					const systemPrompt = this.buildGroupChatPrompt(null);
					
					// 构建不重复用户消息的历史记录
					const historyWithSystemPrompt = [
						{ role: 'system', content: systemPrompt },
						...historyMessages,
						{ role: 'user', content: userMsg }
					];
					
					await this.$refs.aiChat.sendMessage(userMsg, historyWithSystemPrompt, this.currentModelId);
					
					await this.waitForMessageCompletion(msg.id);
				} catch (error) {
					console.error('[对话] 默认对话出错:', error);
				}
				
				this.isLoading = false;
				return;
			}

			// 实现新的逻辑：按照角色顺序循环
			try {
				// 初始历史记录（不包含系统提示和当前用户消息）
				let currentHistory = [...historyMessages];
				
				currentHistory.push({ role: 'user', content: userMsg });
				
				// 为每个角色创建并发送消息
				for (const role of selectedRoles) {
					// 为当前角色合成群聊prompt
					const rolePrompt = this.buildGroupChatPrompt(role);
					
					// 添加思考中的消息
					const thinkingMsg = this.addThinkingMessage(role.id, role.name);
					
					// 创建带有系统提示的历史记录
					const historyWithSystemPrompt = [
						{ role: 'system', content: rolePrompt },
						...currentHistory
					];
					let sendChange = false;
					if(historyWithSystemPrompt[historyWithSystemPrompt.length - 1].role === 'assistant'){
						historyWithSystemPrompt[historyWithSystemPrompt.length - 1].role = 'user';
						sendChange = true;
					}
					
					// 调用aichat发送消息（不重复发送用户消息，因为已经在历史记录中）
					await this.$refs.aiChat.sendMessage('', historyWithSystemPrompt, role.model || this.currentModelId);
					if(sendChange){
						historyWithSystemPrompt[historyWithSystemPrompt.length - 1].role = 'assistant';
					}
					// 等待消息完成
					await this.waitForMessageCompletion(thinkingMsg.id);
					
					// 检查消息是否已完成
					const completedMsg = this.messages.find(m => m.id === thinkingMsg.id);
					if (completedMsg && !completedMsg.isThinking) {
						// 格式化角色回复
						let messageContent = completedMsg.content || '';
						if (messageContent.startsWith(`${role.name}：`) || messageContent.startsWith(`${role.name}:`)) {
							// 如果以角色名开头，移除重复的角色名
							messageContent = messageContent.substring(role.name.length + 1).trim();
						}
						
						// 更新消息并添加角色名
						const formattedContent = `${role.name}：${messageContent}`;
						this.updateMessage(thinkingMsg.id, {
							content: formattedContent,
							isThinking: false
						});
						
						// 将此回复添加到历史记录中，供下一个角色使用
						currentHistory.push({
							role: 'assistant',
							content: formattedContent
						});
					}
					
					// 小延迟，确保UI更新
					await new Promise(resolve => setTimeout(resolve, 500));
				}
			} catch (error) {
				console.error('[多角色对话] 处理出错:', error);
			} finally {
				this.isLoading = false;
				await this.saveGroupChatHistory();
				this.scrollToBottom(true);
			}
		},

		// 等待消息完成
		async waitForMessageCompletion(messageId, timeout = 60000) {
			return new Promise(resolve => {
				const checkInterval = setInterval(() => {
					const msg = this.messages.find(m => m.id === messageId);
					if (!msg || !msg.isThinking) {
						clearInterval(checkInterval);
						resolve();
					}
				}, 500);

				setTimeout(() => {
					clearInterval(checkInterval);
					const msg = this.messages.find(m => m.id === messageId);
					if (msg?.isThinking) {
						this.updateMessage(msg.id, {
							isThinking: false,
							content: `${msg.roleName || 'AI'}：[响应超时]`
						});
					}
					resolve();
				}, timeout);
			});
		},

		// 发送消息
		async sendMessage() {
			if (this.isLoading || !this.inputMessage.trim()) return;
			
			const userMessage = this.inputMessage.trim();
			this.inputMessage = '';
			this.inputMessagekey++;
			
			// 添加用户消息到UI
			this.addUserMessage(userMessage);
			
			// 隐藏键盘和输入框
			uni.hideKeyboard();
			this.isInputActive = false;
			
			// 获取未包含当前用户消息的历史记录
			const historyMessages = this.getCompletedMessages().slice(0, -1);
			
			// 处理多角色对话
			await this.processMultiRoleChat(userMessage, historyMessages);
		},

		// 返回上一页
		goBack() {
			uni.navigateBack();
		},

		// 跳转到模型选择页面
		goToModelSelect() {
			uni.navigateTo({
				url: '/pages/model/select'
			});
		},

		// 清除聊天记录
		clearHistory() {
			if (!this.currentGroupId) return;
			
			uni.showModal({
				title: '清除聊天记录',
				content: '确定要清除所有聊天记录吗？此操作不可恢复。',
				success: async (res) => {
					if (res.confirm) {
						try {
							// 使用groupChatManager清除群聊历史
							await groupChatManager.clearGroupChatHistory(this.currentGroupId);
							
							// 清空当前消息列表
							this.messages = [];
							
							// 关闭菜单
							this.showGroupMenu = false;
							
							uni.showToast({
								title: '已清除聊天记录',
								icon: 'success'
							});
						} catch (error) {
							console.error('[群聊] 清除聊天记录失败:', error);
							uni.showToast({
								title: '清除失败',
								icon: 'none'
							});
						}
					}
				}
			});
		},

		// 处理编辑消息
		handleEditMessage(message) {
			// 设置当前选中的消息
			this.selectedMessage = message;

			// 设置编辑内容
			this.editingContent = message.content;

			// 显示编辑抽屉
			this.showEditDrawer = true;
		},

		// 确认编辑消息
		async confirmEditMessage() {
			if (!this.selectedMessage) {
				this.showEditDrawer = false;
				return;
			}

			const newContent = this.editingContent.trim();
			if (newContent === this.selectedMessage.content) {
				this.showEditDrawer = false;
				return;
			}

			// 关闭编辑抽屉并清理状态
			this.showEditDrawer = false;
			this.editingContent = '';

			// 更新当前消息
			this.updateMessage(this.selectedMessage.id, {
				content: newContent
			});

			// 找到消息索引
			const msgIndex = this.messages.findIndex(msg => msg.id === this.selectedMessage.id);
			if (msgIndex !== -1) {
				// 删除该消息之后的所有消息
				this.messages = this.messages.slice(0, msgIndex + 1);
				
				// 获取更新后的历史消息，因为我们已经更新了UI中的用户消息，需要避免重复
				// 在这种情况下，用户编辑的消息已经在UI中更新并包含在getCompletedMessages中
				// 所以我们需要排除最后一条消息
				const historyMessages = this.getCompletedMessages().slice(0, -1);
				
				// 处理多角色对话
				await this.processMultiRoleChat(newContent, historyMessages);
			}

			uni.showToast({
				title: '已更新消息',
				icon: 'success',
				duration: 1500
			});

			this.selectedMessage = null;
		},

		// 处理复制消息
		handleCopyMessage(message) {
			// 关闭抽屉
			this.showActionDrawer = false;

			// 复制消息内容
			uni.setClipboardData({
				data: message.content,
				success: () => {
					uni.showToast({
						title: '已复制到剪贴板',
						icon: 'success'
					});
				}
			});
		},

		// 处理删除消息
		handleDeleteMessage(message) {
			// 关闭抽屉
			this.showActionDrawer = false;

			// 确认删除
			this.confirmDeleteMessage(message);
		},

		// 确认删除消息
		confirmDeleteMessage(message) {
			uni.showModal({
				title: '确认删除',
				content: '确定要删除这条消息吗？',
				success: (res) => {
					if (res.confirm) {
						const msgIndex = this.messages.indexOf(message);

						// 删除消息
						this.removeMessage(message.id);

						// 如果删除的是用户消息，询问是否需要删除相关的AI回复
						if (message.type === MessageType.USER && msgIndex !== -1 && msgIndex < this
							.messages.length - 1) {
							// 检查下一条消息是否是AI回复
							const nextMsg = this.messages[msgIndex];
							if (nextMsg && nextMsg.type === MessageType.ASSISTANT) {
								uni.showModal({
									title: '删除相关回复',
									content: '是否同时删除AI的回复？',
									success: (res) => {
										if (res.confirm) {
											this.removeMessage(nextMsg.id);
										}
									}
								});
							}
						}
					}
				}
			});
		},

		// 查找最后一条用户消息的索引
		findLastUserMessageIndex() {
			for (let i = this.messages.length - 1; i >= 0; i--) {
				if (this.messages[i].type === MessageType.USER) {
					return i;
				}
			}
			return -1;
		},

		// 处理模型变化
		handleModelChanged() {
			console.log('[模型] 模型已更改为:', this.currentModelId);
		},

		// 处理SSE关闭事件
		handleSSEClosed() {
			console.log('[SSE] 连接已关闭');
			this.isLoading = false;
			this.retryCount = 0;

			// 获取最后一条消息
			const lastMessage = this.getLastMessage();

			// 首先确保消息不再处于思考状态
			if (lastMessage) {
				// 如果是空消息且处于思考状态，则删除
				if (lastMessage.isThinking && (!lastMessage.content || lastMessage.content.trim() === '')) {
					console.log('[SSE] 删除空的思考消息');
					this.removeMessage(lastMessage.id);
				}
				// 如果消息有内容并且处于思考状态，则更新状态
				else if (lastMessage.isThinking) {
					console.log('[SSE] 更新消息状态为完成');
					
					// 获取角色名称，如果有
					let roleName = "";
					if (lastMessage.roleName) {
						roleName = lastMessage.roleName;
					} else if (lastMessage.roleId) {
						// 尝试从角色ID获取角色名称
						const role = this.groupChatRoles.find(r => r.id === lastMessage.roleId);
						if (role) {
							roleName = role.name;
						}
					}
					
					// 更新消息内容，添加响应中断标记
					if (roleName) {
						this.updateMessage(lastMessage.id, {
							isThinking: false,
							content: `${roleName}：[响应中断]`,
							isReasoningExpanded: true
						});
					} else {
						this.updateMessage(lastMessage.id, {
							isThinking: false,
							content: lastMessage.content || '[响应中断]',
							isReasoningExpanded: true
						});
					}

					// 发出消息更新事件，确保UI更新
					this.$emit('messages-updated', this.messages);

					// 滚动到底部
					this.scrollToBottom(true);
				}
				// 即使消息已经完成，也记录日志
				else {
					console.log('[SSE] 消息已经是完成状态');
				}
			}

			// 检查所有处于思考状态的消息
			const thinkingMessages = this.messages.filter(msg => msg.isThinking);
			if (thinkingMessages.length > 0) {
				console.log(`[SSE] 发现 ${thinkingMessages.length} 条处于思考状态的消息，将它们标记为完成`);
				thinkingMessages.forEach(msg => {
					// 获取角色名称，如果有
					let roleName = "";
					if (msg.roleName) {
						roleName = msg.roleName;
					} else if (msg.roleId) {
						// 尝试从角色ID获取角色名称
						const role = this.groupChatRoles.find(r => r.id === msg.roleId);
						if (role) {
							roleName = role.name;
						}
					}
					
					// 更新消息内容，添加响应中断标记
					if (roleName) {
						this.updateMessage(msg.id, {
							isThinking: false,
							content: `${roleName}：[响应中断]`
						});
					} else {
						this.updateMessage(msg.id, {
							isThinking: false,
							content: msg.content || '[响应中断]'
						});
					}
				});

				// 发出消息更新事件，确保UI更新
				this.$emit('messages-updated', this.messages);

				// 滚动到底部
				this.scrollToBottom(true);
			}
		},

		// 处理输入事件
		handleInput(e) {
			this.inputMessage = e.detail.value;
		},

		// 激活输入框
		activateInput() {
			this.isInputActive = true;
		},

		// 处理输入框失焦
		handleInputBlur() {
			// 使用更短的延迟确保键盘收起后再重置输入框状态
			setTimeout(() => {
				// 主动隐藏键盘
				uni.hideKeyboard();
				this.isInputActive = false;
			}, 50);
		},

		// 监听键盘高度变化
		keyBodyHeightWatch(res) {
			this.jianpanHeight = res.height;
			if (this.jianpanHeight === 0 && this.isInputActive) {
				console.log('[键盘] 键盘高度为0，重置输入框状态');
				// 延迟一点时间后重置输入框状态，确保界面已经更新
				setTimeout(() => {
					this.isInputActive = false;
				}, 50);
			}
		},

		// 处理页面触摸事件
		handlePageTouch(e) {
			// 如果输入框处于激活状态，点击页面任意位置将其关闭
			if (this.isInputActive) {
				this.isInputActive = false;
			}
		},

		// 加载高级角色列表
		loadAdultRoles() {
			try {
				// 使用角色管理器获取成人角色列表
				this.adultRoles = roleManager.getAdultRolesSync() || [];
				console.log('[高级角色] 已加载高级角色列表，数量:', this.adultRoles.length);
			} catch (error) {
				console.error('[高级角色] 加载高级角色列表失败:', error);
				this.adultRoles = [];
			}
		},

		// 检查角色是否被选中
		isRoleSelected(roleId) {
			// 确保类型一致（都转为字符串比较）
			const stringRoleId = String(roleId);
			return this.selectedRoles.some(id => String(id) === stringRoleId);
		},

		// 切换角色选择状态
		toggleRoleSelection(roleId) {
			// 确保roleId是字符串类型
			const stringRoleId = String(roleId);
			const index = this.selectedRoles.findIndex(id => String(id) === stringRoleId);
			
			if (index === -1) {
				// 添加到选中列表
				this.selectedRoles.push(stringRoleId);
			} else {
				// 确保至少保留一个角色
				if (this.selectedRoles.length <= 1) {
					uni.showToast({
						title: '群聊至少需要1个角色',
						icon: 'none',
						duration: 1500
					});
					return;
				}
				// 从选中列表中移除
				this.selectedRoles.splice(index, 1);
			}
			
			// 如果是群聊模式，更新群聊角色列表
			if (this.currentGroupId) {
				try {
					groupChatManager.setGroupChatRoleIds(this.currentGroupId, this.selectedRoles);
					console.log('[群聊] 已更新群聊角色ID列表:', this.selectedRoles);
				} catch (error) {
					console.error('[群聊] 更新群聊角色ID列表失败:', error);
				}
			}
			
			console.log('[群聊] 更新选中角色列表:', this.selectedRoles);
		},

		// 获取选中的高级角色信息（按选择顺序排序）
		getSelectedAdultRolesInfo() {
			// 根据选择顺序过滤和排序角色列表
			if (!this.selectedRoles || this.selectedRoles.length === 0) {
				console.log('[群聊] 没有选中角色，返回空数组');
				return [];
			}
			
			const selectedRoleInfos = [];
			const validRoleIds = [];
			
			console.log('[群聊] 当前选中的角色ID:', this.selectedRoles);
			console.log('[群聊] 群聊中可用的角色数量:', this.groupChatRoles.length);
			
			// 遍历selectedRoles，确保角色存在于groupChatRoles中
			for (const roleId of this.selectedRoles) {
				// 确保roleId是字符串类型用于比较
				const stringRoleId = String(roleId);
				
				// 查找该ID在群聊角色中是否存在
				const role = this.groupChatRoles.find(r => String(r.id) === stringRoleId);
				
				if (role) {
					selectedRoleInfos.push(role);
					validRoleIds.push(stringRoleId);
				} else {
					console.warn(`[群聊] 角色ID ${stringRoleId} 不在群聊角色列表中，将被忽略`);
				}
			}
			
			// 如果有无效角色，更新selectedRoles
			if (validRoleIds.length < this.selectedRoles.length) {
				console.log(`[群聊] 更新选中角色列表 ${this.selectedRoles.length} -> ${validRoleIds.length}`);
				this.selectedRoles = validRoleIds;
				
				// 如果是群聊模式，更新群聊角色列表
				if (this.currentGroupId) {
					try {
						// 更新群聊角色ID列表
						groupChatManager.setGroupChatRoleIds(this.currentGroupId, validRoleIds);
						console.log('[群聊] 已更新群聊角色ID列表');
					} catch (error) {
						console.error('[群聊] 更新群聊角色ID列表失败:', error);
					}
				}
			}
			
			console.log('[群聊] 最终选中的有效角色数量:', selectedRoleInfos.length);
			return selectedRoleInfos;
		},

		// 获取角色顺序
		getRoleOrder(roleId) {
			// 确保类型一致（都转为字符串比较）
			const stringRoleId = String(roleId);
			return this.selectedRoles.findIndex(id => String(id) === stringRoleId) + 1;
		},

		// 加载群聊信息
		async loadGroupChatInfo(groupId) {
			try {
				console.log('[群聊] 正在加载群聊信息:', groupId);
				// 设置当前群聊ID
				this.currentGroupId = groupId;
				
				// 获取群聊信息
				const groupChat = await groupChatManager.getGroupById(groupId);
				
				if (!groupChat) {
					console.error('[群聊] 群聊不存在:', groupId);
					this.showErrorAndNavigateBack('群聊不存在');
					return;
				}
				
				console.log('[群聊] 群聊信息:', groupChat);
				
				// 设置群聊标题
				this.roleName = groupChat.name || '群聊';
				
				// 加载群聊角色
				await this.loadGroupChatRoles(groupId);
				
				// 加载群聊历史
				await this.loadGroupChatHistory(groupId);
				
				// 设置默认选中的角色（确保使用字符串类型的ID）
				this.selectedRoles = groupChat.roleIds.map(id => String(id));
				
				// 加载高级角色列表
				this.loadAdultRoles();
			} catch (error) {
				console.error('[群聊] 加载群聊信息失败:', error);
				this.showErrorAndNavigateBack('加载群聊信息失败');
			}
		},
		
		// 加载群聊角色
		async loadGroupChatRoles(groupId) {
			try {
				// 使用groupChatManager获取群聊角色
				const roles = await groupChatManager.getGroupChatRoles(groupId);
				this.groupChatRoles = roles || [];
				
				// 获取可添加的角色
				this.availableRoles = await groupChatManager.getAvailableRolesForGroupChat(groupId);
				
				console.log('[群聊] 群聊角色:', this.groupChatRoles.length, '可添加角色:', this.availableRoles.length);
			} catch (error) {
				console.error('[群聊] 加载群聊角色失败:', error);
				uni.showToast({
					title: '加载角色失败',
					icon: 'none'
				});
			}
		},
		
		// 加载群聊历史
		async loadGroupChatHistory(groupId) {
			try {
				// 使用groupChatManager获取群聊历史
				const history = await groupChatManager.getGroupChatHistory(groupId);
				if (history && history.length > 0) {
					// 为每条消息添加处理推理展开状态的属性
					this.messages = history.map(msg => ({
						...msg,
						isReasoningExpanded: false
					}));
					console.log('[群聊] 已加载历史消息:', this.messages.length);
					
					// 确保在下一个渲染周期后滚动到底部
					this.$nextTick(() => {
						this.scrollToBottom(false);
					});
				} else {
					console.log('[群聊] 没有历史消息');
					this.messages = [];
				}
			} catch (error) {
				console.error('[群聊] 加载历史消息失败:', error);
				this.messages = [];
			}
		},
		
		// 保存群聊历史
		async saveGroupChatHistory() {
			if (!this.currentGroupId) return;
			
			try {
				// 过滤出非思考中的消息
				const completedMessages = this.messages.filter(msg => !msg.isThinking);
				
				// 使用groupChatManager保存群聊历史
				await groupChatManager.saveGroupChatHistory(this.currentGroupId, completedMessages);
				console.log('[群聊] 已保存历史消息:', completedMessages.length);
			} catch (error) {
				console.error('[群聊] 保存历史消息失败:', error);
			}
		},
		
		// 添加角色到群聊
		async addRoleToChat(roleId) {
			if (!this.currentGroupId) return;
			
			try {
				// 确保roleId是字符串类型
				const roleIdStr = String(roleId);
				
				// 使用groupChatManager添加角色
				const success = await groupChatManager.addRoleToGroupChat(this.currentGroupId, roleIdStr);
				
				if (success) {
					console.log('[群聊] 添加角色成功:', roleIdStr);
					// 重新加载群聊角色
					await this.loadGroupChatRoles(this.currentGroupId);
					// 添加到选中角色列表（如果不存在）
					if (!this.selectedRoles.includes(roleIdStr)) {
						this.selectedRoles.push(roleIdStr);
					}
				} else {
					console.error('[群聊] 添加角色失败:', roleIdStr);
					uni.showToast({
						title: '添加角色失败',
						icon: 'none'
					});
				}
			} catch (error) {
				console.error('[群聊] 添加角色异常:', error);
				uni.showToast({
					title: '添加角色失败',
					icon: 'none'
				});
			}
		},
		
		// 从群聊中移除角色
		async removeRoleFromChat(roleId) {
			if (!this.currentGroupId) return;
			
			try {
				// 确保roleId是字符串类型
				const roleIdStr = String(roleId);
				
				// 使用groupChatManager移除角色
				const success = await groupChatManager.removeRoleFromGroupChat(this.currentGroupId, roleIdStr);
				
				if (success) {
					console.log('[群聊] 移除角色成功:', roleIdStr);
					// 重新加载群聊角色
					await this.loadGroupChatRoles(this.currentGroupId);
					// 从选中角色列表移除
					this.selectedRoles = this.selectedRoles.filter(id => id !== roleIdStr);
				} else {
					console.error('[群聊] 移除角色失败:', roleIdStr);
					uni.showToast({
						title: '移除角色失败',
						icon: 'none'
					});
				}
			} catch (error) {
				console.error('[群聊] 移除角色异常:', error);
				uni.showToast({
					title: '移除角色失败',
					icon: 'none'
				});
			}
		},

		// 检查是否开启沉浸模式
		checkImmersiveMode() {
			const immersiveMode = settingsManager.immersiveMode;
			this.showImmersiveBackground = immersiveMode;
			console.log('[沉浸模式] 当前状态:', immersiveMode);
			
			// 设置背景色
			if (immersiveMode) {
				this.containerStyle = {
					backgroundColor: 'transparent'
				};
				this.messageListStyle = {
					backgroundColor: 'transparent'
				};
			} else {
				this.containerStyle = {
					backgroundColor: 'rgb(18, 18, 20)'
				};
				this.messageListStyle = {
					backgroundColor: 'rgb(18, 18, 20)'
				};
			}
		},
		
		// 处理设置变更事件
		handleSettingsChange(event) {
			console.log('[设置] 设置已变更:', event);
			
			// 检查沉浸模式设置是否发生变化
			if (event && event.type === 'immersiveMode') {
				this.checkImmersiveMode();
			}
		},

		// 显示群聊菜单
		showGroupChatMenu() {
			this.showGroupMenu = true;
		},

		// 显示角色管理器
		showRoleManager() {
			// 关闭群聊菜单
			this.showGroupMenu = false;

			// 确保有当前群聊ID
			if (!this.currentGroupId) {
				uni.showToast({
					title: '无法获取群聊信息',
					icon: 'none'
				});
				return;
			}

			// 克隆当前角色列表到临时存储，用于后续编辑
			this.tempGroupChatRoles = JSON.parse(JSON.stringify(this.groupChatRoles));
			this.tempAvailableRoles = JSON.parse(JSON.stringify(this.availableRoles));
			this.pendingRoleChanges = false;

			// 显示角色管理模态框
			this.showRoleManagerModal = true;
		},

		// 添加角色到群聊（本地临时操作）
		addRoleToChat(roleId) {
			// 在临时存储中查找角色
			const roleIndex = this.tempAvailableRoles.findIndex(role => role.id === roleId);
			if (roleIndex === -1) return;
			
			// 从可用角色中移除并添加到群聊角色
			const role = this.tempAvailableRoles.splice(roleIndex, 1)[0];
			this.tempGroupChatRoles.push(role);
			
			// 标记有待处理的更改
			this.pendingRoleChanges = true;
			
			console.log('[群聊] 临时添加角色:', roleId);
		},

		// 从群聊中移除角色（本地临时操作）
		removeRoleFromChat(roleId) {
			// 在临时存储中查找角色
			const roleIndex = this.tempGroupChatRoles.findIndex(role => role.id === roleId);
			if (roleIndex === -1) return;
			
			// 从群聊角色中移除并添加到可用角色
			const role = this.tempGroupChatRoles.splice(roleIndex, 1)[0];
			this.tempAvailableRoles.push(role);
			
			// 标记有待处理的更改
			this.pendingRoleChanges = true;
			
			console.log('[群聊] 临时移除角色:', roleId);
		},

		// 确认角色变更并提交
		async confirmRoleChanges() {
			// 如果没有待处理的更改，直接关闭模态框
			if (!this.pendingRoleChanges) {
				this.showRoleManagerModal = false;
				return;
			}
			
			// 显示加载状态
			uni.showLoading({
				title: '保存中...',
				mask: true
			});
			
			try {
				// 获取当前群聊角色ID列表（确保是字符串类型）
				const newRoleIds = this.tempGroupChatRoles.map(role => String(role.id));
				
				// 更新群聊角色
				const success = await groupChatManager.updateGroupChatRoles(this.currentGroupId, newRoleIds);
				
				if (success) {
					console.log('[群聊] 角色更新成功');
					
					// 更新本地角色列表
					this.groupChatRoles = [...this.tempGroupChatRoles];
					this.availableRoles = [...this.tempAvailableRoles];
					
					// 更新选中角色列表（确保使用字符串类型）
					this.selectedRoles = this.selectedRoles.filter(roleId => 
						this.groupChatRoles.some(role => String(role.id) === String(roleId))
					);
					
					uni.showToast({
						title: '角色已更新',
						icon: 'success'
					});
				} else {
					console.error('[群聊] 角色更新失败');
					uni.showToast({
						title: '更新失败',
						icon: 'none'
					});
					
					// 恢复原始数据
					await this.loadGroupChatRoles(this.currentGroupId);
				}
			} catch (error) {
				console.error('[群聊] 更新角色异常:', error);
				uni.showToast({
					title: '更新失败',
					icon: 'none'
				});
				
				// 恢复原始数据
				await this.loadGroupChatRoles(this.currentGroupId);
			} finally {
				uni.hideLoading();
				this.pendingRoleChanges = false;
				this.showRoleManagerModal = false;
			}
		},

		// 取消角色变更
		cancelRoleChanges() {
			// 如果有待处理的更改，显示确认对话框
			if (this.pendingRoleChanges) {
				uni.showModal({
					title: '取消更改',
					content: '您有未保存的更改，确定要放弃这些更改吗？',
					success: (res) => {
						if (res.confirm) {
							this.showRoleManagerModal = false;
							this.pendingRoleChanges = false;
						}
						// 如果用户点击取消，不关闭模态框，继续编辑
					}
				});
			} else {
				// 如果没有待处理的更改，直接关闭
				this.showRoleManagerModal = false;
				this.pendingRoleChanges = false;
			}
		},
	}
}
</script>

<style>
:root {
	--primary-color-rgb: 212, 165, 32;
	--text-color-rgb: 255, 255, 255;
	--border-color-rgb: 255, 255, 255;
	--card-bg-color-rgb: 44, 44, 46;
	--bg-color-rgb: 18, 18, 20;
	--nav-bg-color: rgba(18, 18, 20, 0.9);
	--text-on-primary-color: #000000;
	--text-secondary-color: #86868b;
	--card-bg-color: #2c2c2e;
	--border-color: rgba(255, 255, 255, 0.1);
	--input-bg-color: #3a3a3c;
}

/* 沉浸模式相关样式 */
.chat-container {
	position: relative;
	width: 100%;
	min-height: 100vh;
	background-color: transparent; /* 当开启沉浸模式时应该是透明的 */
	overflow-y: auto;
	font-family: -apple-system, BlinkMacSystemFont, 'Helvetica Neue', Helvetica, sans-serif;
	color: #ffffff;
}

/* 沉浸模式下的导航栏样式 */
.ios18-navbar.immersive-navbar {
	background-color: transparent;
	backdrop-filter: blur(5px);
	-webkit-backdrop-filter: blur(5px);
	border-bottom: none;
	box-shadow: none;
}

/* 沉浸模式下的按钮样式 */
.nav-button.immersive-button {
	background-color: rgba(0, 0, 0, 0.2);
	backdrop-filter: blur(5px);
	-webkit-backdrop-filter: blur(5px);
}

/* 沉浸模式下的选择器样式 */
.role-model-selector.immersive-selector {
	background-color: rgba(0, 0, 0, 0.2);
	backdrop-filter: blur(5px);
	-webkit-backdrop-filter: blur(5px);
	padding: 8px 16px;
}

/* 沉浸模式下的消息列表样式 */
.immersive-message-list {
	padding: 16rpx 24rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	min-height: 70vh;
}

/* 沉浸模式下的消息列表遮罩 */
.chat-container.immersive-background .message-list {
	position: relative;
}

.chat-container.immersive-background .message-list::after {
	content: '';
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	height: 70vh;
	background: linear-gradient(to bottom, 
		rgba(18, 18, 20, 0) 0%,
		rgba(18, 18, 20, 0.8) 50%,
		rgba(18, 18, 20, 1) 100%
	);
	pointer-events: none;
	z-index: 2;
}

/* 沉浸模式下的消息列表容器 */
.chat-container.immersive-background .messages-container {
	position: relative;
	z-index: 3;
}

/* 沉浸模式下的消息样式 */
.message.immersive-message {
	margin-bottom: 0;
	width: 100%;
}

.message.immersive-message .message-content {
	max-width: 90%;
	margin: 0 auto;
}

/* 沉浸模式下的消息内容样式 */
.message-content.immersive-content {
	background-color: transparent;
	backdrop-filter: none;
	-webkit-backdrop-filter: none;
	border: none;
	box-shadow: none;
}

.message.assistant .message-content.immersive-content {
	border-radius: 0;
	padding: 20rpx 40rpx;
}

.user-message.immersive-content {
	background-color: transparent;
}

/* 沉浸模式下的输入容器样式 */
.ios18-input-container.immersive-input {
	background-color: rgba(18, 18, 20, 0.4);
	backdrop-filter: blur(5px);
	-webkit-backdrop-filter: blur(5px);
	border-top: none;
	box-shadow: none;
	padding: 12px;
}

/* 沉浸模式下的输入框包装器样式 */
.input-wrapper.immersive-wrapper {
	background-color: rgba(58, 58, 60, 0.5);
	box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* 激活状态的输入框包装器样式 */
.active-input-wrapper.immersive-wrapper {
	background-color: rgba(58, 58, 60, 0.5);
	box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* iOS 18 风格导航栏 */
.ios18-navbar {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	backdrop-filter: blur(10px);
	-webkit-backdrop-filter: blur(10px);
	z-index: 100;
	border-bottom: 0.5rpx solid rgba(255, 255, 255, 0.1);
	box-shadow: 0 4rpx 8rpx rgba(0, 0, 0, 0.2);
}

.navbar-content {
	height: 44px;
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 0 8px;
}

.navbar-left,
.navbar-right {
	width: 44px;
	height: 44px;
	display: flex;
	align-items: center;
	justify-content: center;
}

.nav-button {
	width: 36px;
	height: 36px;
	display: flex;
	align-items: center;
	justify-content: center;
	border-radius: 18px;
	background-color: rgba(255, 255, 255, 0.05);
	transition: all 0.2s ease;
}

.nav-button:active {
	background-color: rgba(255, 255, 255, 0.1);
	transform: scale(0.95);
}

.navbar-center {
	flex: 1;
	display: flex;
	align-items: center;
	justify-content: center;
}

.role-model-selector {
	display: flex;
	align-items: center;
	gap: 6px;
	padding: 6px 12px;
	border-radius: 16px;
	transition: background-color 0.2s ease;
}

.role-model-selector:active {
	background-color: rgba(255, 255, 255, 0.05);
}

.role-name {
	font-size: 18px;
	color: #ffffff;
	font-weight: 600;
	margin-right: 8px;
}

.model-name {
	font-size: 14px;
	color: #86868b;
	font-weight: 500;
}

/* 消息列表区域 */
.message-list {
	position: relative;
	width: 100%;
	margin-top: var(--navbar-height, 76px);
	margin-bottom: 120rpx;
	padding: 16rpx 32rpx;
	background-color: transparent;
	z-index: 1;
	padding-bottom: 160rpx; /* 确保底部有足够空间 */
	transition: all 0.3s ease;
}

/* 消息容器 */
.messages-container {
	display: flex;
	flex-direction: column;
	width: 100%;
	padding-bottom: 16rpx;
}

.message {
	display: flex;
	flex-direction: column;
	margin-bottom: 16rpx;
}

.message.user {
	align-items: flex-end;
}

.message.assistant {
	align-items: stretch;
	margin: 0 -16px;
}

.assistant-message {
	width: 100%;
	max-width: 100%;
	color: #ffffff;
	border-radius: 0;
	box-shadow: none;
	backdrop-filter: none;
	-webkit-backdrop-filter: none;
}

.user-message {
	max-width: 75%;
	color: #ffffff;
	border-top-right-radius: 4rpx;
	border-radius: 20rpx;
	box-shadow: none;
}

.message-content {
	border-radius: 20rpx;
	padding: 16rpx 24rpx;
	word-break: break-word;
	position: relative;
	transition: opacity 0.2s, transform 0.2s;
}

.message.assistant .message-content {
	border-radius: 0;
}

.message.assistant .message-actions {
	padding: 0 40rpx;
}

.reasoning-card {
	border-radius: 12px;
	margin: 0 0 4px 0;
	overflow: hidden;
	border: none;
	background-color: transparent;
	margin-bottom: -48rpx;
}

.reasoning-header {
	padding: 6px 12px;
	display: flex;
	align-items: center;
	cursor: pointer;
}

.reasoning-icon {
	transition: transform 0.3s;
}

.reasoning-title {
	font-size: 14px;
	color: #ffffff;
	font-weight: 500;
}

.reasoning-body {
	padding: 0 12px 6px;
	font-size: 14px;
	color: #86868b;
	transition: max-height 0.3s;
}

.collapsed {
	max-height: 0;
	padding: 0 12px;
	overflow: hidden;
}

.expanded .reasoning-body {
	max-height: 1000px;
}

.answer-content {
	margin-top: 4px;
}

/* 思考动画 */
.thinking .message-content {
	position: relative;
}

.thinking-dots {
	display: flex;
	padding: 5px 0;
}

.thinking-dots text {
	font-size: 24px;
	line-height: 1;
	animation: thinking-animation 1.4s infinite;
	margin-right: 2px;
}

.thinking-dots text:nth-child(2) {
	animation-delay: 0.2s;
}

.thinking-dots text:nth-child(3) {
	animation-delay: 0.4s;
}

@keyframes thinking-animation {
	0%,
	60%,
	100% {
		transform: translateY(0);
		opacity: 0.3;
	}

	30% {
		transform: translateY(-4px);
		opacity: 1;
	}
}

.thinking .assistant-message {
	opacity: 0.7;
}

/* 消息操作按钮样式 */
.message-actions {
	display: flex;
	justify-content: flex-end;
	margin-top: 4px;
	padding: 0 4px;
	opacity: 0.85;
}

.message.user .message-actions {
	justify-content: flex-end;
}

.message.assistant .message-actions {
	justify-content: flex-start;
}

.action-buttons {
	display: flex;
	gap: 8px;
	height: 28px;
}

.action-btn {
	width: 28px;
	height: 28px;
	display: flex;
	align-items: center;
	justify-content: center;
	border-radius: 14px;
	background-color: rgba(255, 255, 255, 0.05);
	box-shadow: none;
	transition: all 0.2s ease;
}

.action-btn:active {
	transform: scale(0.92);
	opacity: 0.6;
	background-color: rgba(255, 255, 255, 0.1);
}

/* iOS 18 风格输入区域 */
.ios18-input-container {
	position: fixed;
	left: 0;
	right: 0;
	bottom: 0;
	padding: 4px;
	background-color: rgba(18, 18, 20, 0.9);
	backdrop-filter: blur(10px);
	-webkit-backdrop-filter: blur(10px);
	display: flex;
	flex-direction: column;
	border-top: 1px solid rgba(255, 255, 255, 0.1);
	z-index: 100;
	box-shadow: 0 -2rpx 4rpx rgba(0, 0, 0, 0.2);
	/* #ifdef APP-PLUS */
	padding-bottom: calc(4px + constant(safe-area-inset-bottom));
	padding-bottom: calc(4px + env(safe-area-inset-bottom));
	/* #endif */
	transition: all 0.3s ease;
}

.input-wrapper {
	display: flex;
	align-items: flex-end;
	width: 100%;
	background-color: rgba(58, 58, 60, 0.5);
	border-radius: 16px;
	padding: 2px 2px 2px 8px;
	box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
	transition: all 0.3s ease;
}

/* 未激活状态的输入框样式 */
.inactive-input-box {
	flex: 1;
	min-height: 28px;
	font-size: 14px;
	line-height: 16px;
	color: #86868b;
	display: flex;
	align-items: center;
}

.input-placeholder {
	color: #86868b;
}

.ios18-input-box {
	flex: 1;
	max-height: 80px;
	font-size: 14px;
	line-height: 16px;
	color: #ffffff;
	background-color: transparent;
	padding: 4px 0;
}

/* 添加输入框占位符文本颜色样式 */
.ios18-input-box::placeholder {
	color: #86868b;
}

/* 激活状态的输入框包装器样式 */
.active-input-wrapper {
	position: fixed;
	z-index: 101;
	background-color: rgba(58, 58, 60, 0.5);
	box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
	left: 4px;
	right: 4px;
	width: auto;
	transition: all 0.3s ease;
}

.send-button-wrapper {
	margin-left: 4px;
	transition: transform 0.2s ease;
}

.send-active {
	transform: scale(1.05);
}

.ios18-send-btn {
	width: 32px;
	height: 32px;
	border-radius: 16px;
	padding: 0;
	display: flex;
	align-items: center;
	justify-content: center;
	transition: transform 0.2s ease;
}

.send-button-wrapper.send-active .ios18-send-btn {
	transform: scale(1.05);
}

/* 操作抽屉样式 */
.action-drawer {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background-color: rgba(0, 0, 0, 0.5);
	z-index: 1000;
	display: flex;
	flex-direction: column;
	justify-content: flex-end;
	backdrop-filter: blur(8px);
	-webkit-backdrop-filter: blur(8px);
}

.action-drawer-panel {
	background-color: #2c2c2e;
	border-radius: 32rpx 32rpx 0 0;
	padding: 24rpx 0;
	transform: translateY(100%);
	transition: transform 0.3s cubic-bezier(0.16, 1, 0.3, 1);
	box-shadow: 0 -4rpx 24rpx rgba(0, 0, 0, 0.3);
}

.drawer-show {
	transform: translateY(0);
}

.drawer-header {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 24rpx 32rpx;
	border-bottom: 1px solid rgba(255, 255, 255, 0.1);
	margin-bottom: 16rpx;
}

.drawer-title {
	font-size: 34rpx;
	font-weight: 600;
	color: #ffffff;
}

.drawer-close {
	width: 64rpx;
	height: 64rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	border-radius: 32rpx;
	background-color: rgba(255, 255, 255, 0.05);
	transition: all 0.2s ease;
}

.drawer-close:active {
	background-color: rgba(255, 255, 255, 0.1);
	transform: scale(0.95);
}

.action-drawer-content {
	padding: 8rpx 16rpx;
}

.action-item {
	display: flex;
	align-items: center;
	padding: 24rpx 32rpx;
	margin: 8rpx 16rpx;
	border-radius: 20rpx;
	background-color: #3a3a3c;
	transition: all 0.2s ease;
}

.action-item:active {
	background-color: rgba(255, 255, 255, 0.05);
	transform: scale(0.98);
}

.action-item.delete {
	color: #ff453a;
}

.action-item.delete my-icon {
	color: #ff453a;
}

.action-item.cancel {
	margin-top: 24rpx;
	background-color: rgba(255, 255, 255, 0.05);
}

.action-item-text {
	margin-left: 24rpx;
	font-size: 32rpx;
	color: #ffffff;
}

.action-item.delete .action-item-text {
	color: #ff453a;
}

/* 编辑模态框样式 */
.edit-modal-mask {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background-color: rgba(0, 0, 0, 0.4);
	z-index: 1000;
	display: flex;
	align-items: center;
	justify-content: center;
}

.edit-modal-container {
	width: 90%;
	background-color: #2c2c2e;
	border-radius: 24rpx;
	transform: scale(0.9);
	opacity: 0;
	transition: all 0.3s ease-out;
}

.modal-show {
	transform: scale(1);
	opacity: 1;
}

.modal-header {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 32rpx;
	border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

.modal-title {
	font-size: 32rpx;
	font-weight: 600;
	color: #ffffff;
}

.modal-close {
	padding: 16rpx;
	margin: -16rpx;
}

.modal-footer {
	padding: 24rpx 32rpx;
	border-top: 1px solid rgba(255, 255, 255, 0.1);
}

.edit-modal-content {
	padding: 32rpx;
}

.edit-textarea {
	width: 100%;
	min-height: 240rpx;
	background-color: #3a3a3c;
	border-radius: 16rpx;
	padding: 24rpx;
	font-size: 28rpx;
	color: #ffffff;
	border: 1px solid rgba(255, 255, 255, 0.1);
}

.edit-textarea::placeholder {
	color: #86868b;
}

.edit-actions {
	display: flex;
	justify-content: flex-end;
	gap: 24rpx;
}

.edit-btn {
	min-width: 160rpx;
	height: 80rpx;
	border-radius: 40rpx;
	font-size: 28rpx;
	font-weight: 500;
	padding: 0 40rpx;
}

.cancel-btn {
	background-color: rgba(255, 255, 255, 0.05) !important;
	color: #ffffff !important;
	border: 1px solid rgba(255, 255, 255, 0.1);
}

/* 高级角色选择器样式 */
.adult-roles-selector {
	margin-bottom: 2px;
	background-color: transparent;
	padding: 2px;
	width: 100%;
}

.roles-scroll {
	width: 100%;
	white-space: nowrap;
}

.roles-list {
	display: inline-flex;
	padding: 1px;
	gap: 2px;
}

.role-item {
	display: inline-flex;
	align-items: center;
	justify-content: center;
	padding: 2px 6px;
	background-color: rgba(58, 58, 60, 0.5);
	border-radius: 10px;
	border: 1px solid rgba(255, 255, 255, 0.1);
	transition: all 0.2s ease;
	position: relative;
	height: 20px;
}

.role-item:active {
	transform: scale(0.95);
}

.role-item.selected {
	background-color: rgba(212, 165, 32, 0.8);
	border-color: rgba(212, 165, 32, 0.8);
	box-shadow: 0 1px 3px rgba(212, 165, 32, 0.2);
	transform: none;
	padding-right: 16px;
}

.role-item.selected:active {
	transform: scale(0.95);
}

.role-item.selected .role-name {
	color: #000000;
}

.role-name {
	font-size: 12px;
	color: #ffffff;
	line-height: 1;
}

.role-order {
	width: 14px;
	height: 14px;
	font-size: 9px;
	margin-left: 2px;
	right: 1px;
	display: flex;
	align-items: center;
	justify-content: center;
	border-radius: 50%;
	background-color: rgba(0, 0, 0, 0.3);
	color: #ffffff;
	font-weight: bold;
	position: absolute;
	top: 50%;
	transform: translateY(-50%);
}

/* 角色管理模态框样式 */
.role-manager-modal {
	max-height: 80vh;
	overflow-y: auto;
}

.role-manager-section {
	margin-bottom: 24rpx;
}

.section-title {
	font-size: 28rpx;
	font-weight: 600;
	color: #ffffff;
	margin-bottom: 16rpx;
}

.role-list {
	display: flex;
	flex-direction: column;
	gap: 16rpx;
}

.role-item-manager {
	display: flex;
	align-items: center;
	padding: 16rpx;
	background-color: #3a3a3c;
	border-radius: 16rpx;
	border: 1px solid rgba(255, 255, 255, 0.1);
}

.role-avatar {
	width: 64rpx;
	height: 64rpx;
	border-radius: 32rpx;
	margin-right: 16rpx;
}

.role-name {
	flex: 1;
	font-size: 28rpx;
	color: #ffffff;
}

.role-action {
	width: 64rpx;
	height: 64rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	border-radius: 32rpx;
	background-color: rgba(255, 255, 255, 0.05);
}

.role-action:active {
	background-color: rgba(255, 255, 255, 0.1);
}

.empty-tip {
	padding: 32rpx;
	text-align: center;
	color: #86868b;
	font-size: 28rpx;
}
</style>